﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Strongshell.Recoil.Core.Composition.Parsing.DependencyInjection;

namespace Strongshell.Recoil.Core.Composition.Parsing.Handlers
{
    public class CompilingHandler : IExpressionHandler
    {
        public void Handle(IDependencyInjector currentInjector, Expression currentExpression)
        {
            var lambdaExpression = currentExpression.NodeType == ExpressionType.Lambda
                                       ? (LambdaExpression)currentExpression
                                       : Expression.Lambda(currentExpression);

            var compiledDelegate = lambdaExpression.Compile();

            var value = lambdaExpression.Parameters.Count > 0
                            ? compiledDelegate.DynamicInvoke(lambdaExpression.Parameters)
                            : compiledDelegate.DynamicInvoke();

            currentInjector.Inject(value);
        }
    }
}
